package com.mall.mall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.mall.common.To.mq.OrderTo;
import com.mall.common.Vo.MemberResponseVo;
import com.mall.common.exception.NoStockException;
import com.mall.common.utils.R;
import com.mall.mall.order.constant.OrderConstant;
import com.mall.mall.order.dao.OrderItemDao;
import com.mall.mall.order.entity.OrderItemEntity;
import com.mall.mall.order.entity.PaymentInfoEntity;
import com.mall.mall.order.enume.OrderStatusEnum;
import com.mall.mall.order.feign.CartFeignService;
import com.mall.mall.order.feign.MemberFeignService;
import com.mall.mall.order.feign.ProductFeignService;
import com.mall.mall.order.feign.WmsFeignService;
import com.mall.mall.order.interceptor.LoginUserIntercepter;
import com.mall.mall.order.service.OrderItemService;
import com.mall.mall.order.service.PaymentInfoService;
import com.mall.mall.order.vo.*;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mall.common.utils.PageUtils;
import com.mall.common.utils.Query;

import com.mall.mall.order.dao.OrderDao;
import com.mall.mall.order.entity.OrderEntity;
import com.mall.mall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    WmsFeignService wmsFeignService;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    PaymentInfoService paymentInfoService;

    @Autowired
    ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 订单确认页返回需要的数据
     * @return
     */
    @Override
    public OrderConfirmVO confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVO orderConfirmVO = new OrderConfirmVO();
        MemberResponseVo loginUser = LoginUserIntercepter.loginUser.get();
        // 获取主线程中的请求头数据
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        // 远程查询所有收获地址
        CompletableFuture<Void> getAddressesTask = CompletableFuture.runAsync(() -> {
            // 为异步线程设置请求头数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<MemberAddressVO> addresses = memberFeignService.getAddresses(loginUser.getId());
            orderConfirmVO.setAddress(addresses);
        }, threadPoolExecutor);

        // 远程查询订单中的所有购物项
        CompletableFuture<Void> getCartItemsTask = CompletableFuture.runAsync(() -> {
            // 为异步线程设置请求头数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVO> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
            orderConfirmVO.setItems(currentUserCartItems);
        }, threadPoolExecutor).thenRunAsync(()->{
            List<OrderItemVO> items = orderConfirmVO.getItems();
            List<Long> collect = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            R skusHasStock = wmsFeignService.getSkusHasStock(collect);
            List<SkuStockVO> data = skusHasStock.getData(new TypeReference<List<SkuStockVO>>() {});
            Map<Long, Boolean> stockMap = data.stream().collect(Collectors.toMap(SkuStockVO::getSkuId, SkuStockVO::getHasStock));
            orderConfirmVO.setStocks(stockMap);
        }, threadPoolExecutor);

        // 查询用户积分
        Integer integration = loginUser.getIntegration();
        orderConfirmVO.setIntegration(integration);

        // 等待两个异步任务完成
        CompletableFuture.allOf(getAddressesTask, getCartItemsTask).get();

        // 防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + loginUser.getId(), token, 30, TimeUnit.MINUTES);
        orderConfirmVO.setOrderToken(token);

        return orderConfirmVO;
    }

    /**
     * 提交下单：创建订单、验证令牌、验价格、锁库存
     * @param vo
     * @return
     */
    @GlobalTransactional
    @Transactional
    @Override
    public SubmitOrderResponseVO submitOrder(OrderSubmitVO vo) {
        SubmitOrderResponseVO responseVO = new SubmitOrderResponseVO();
        MemberResponseVo loginUser = LoginUserIntercepter.loginUser.get();
        responseVO.setCode(0);
        // 1、验证令牌（令牌的对比和删除必须是原子性）
        String orderToken = vo.getOrderToken();
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        // 原子验证令牌和删除令牌
        Long executeResult = (Long) redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + loginUser.getId()),
                orderToken);
        if (0L == executeResult){
            // 令牌验证失败
        }else {
            // 令牌验证成功，创建订单
            OrderCreateTO order = createOrder(vo);
            order.getOrder().setMemberId(loginUser.getId());
            // 验价
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = vo.getPayPrice();
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01){
                // 价格对比成功，保存订单
                saveOrder(order, loginUser);
                // 库存锁定，如果锁定失败则回滚事务
                WareSkuLockVO wareSkuLockVO = new WareSkuLockVO();
                wareSkuLockVO.setOrderSn(order.getOrder().getOrderSn());
                List<OrderItemVO> orderItemVOList = order.getOrderItems().stream().map(item -> {
                    OrderItemVO itemVO = new OrderItemVO();
                    itemVO.setSkuId(item.getSkuId());
                    itemVO.setCount(item.getSkuQuantity());
                    itemVO.setTitle(item.getSkuName());
                    return itemVO;
                }).collect(Collectors.toList());
                wareSkuLockVO.setLocks(orderItemVOList);
                R r = wmsFeignService.orderLockStock(wareSkuLockVO);
//                int b = 10/0;
                if (0 == r.getCode()){
                    // 锁定成功
                    responseVO.setOrder(order.getOrder());
                    // 订单创建成功，发送消息到MQ
                    rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", order.getOrder());
                    return responseVO;
                }else {
                    // 锁定失败
                    responseVO.setCode(3);
                    String msg = (String) r.get("msg");
                    throw new NoStockException(msg);
                }
            }

        }

        return responseVO;
    }

    /**
     * 根据订单号查询订单
     * @param sn
     * @return
     */
    @Override
    public OrderEntity getOrderByOrderSn(String sn) {
        //TODO:order_sn 用的是 UUid，这样差很慢
        return this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", sn));
    }

    @Override
    public void closeOrder(OrderEntity order) {
        // 查询当前订单的最新状态
        OrderEntity byId = this.getById(order);

        if (byId != null && OrderStatusEnum.CREATE_NEW.getCode().equals(byId.getStatus())){
            // 关闭订单
            OrderEntity orderEntity = new OrderEntity();
            orderEntity.setStatus(OrderStatusEnum.CANCLED.getCode());
            orderEntity.setId(byId.getId());
            this.updateById(orderEntity);
            // 发送解锁库存消息
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(byId, orderTo);
            rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderTo);
        }
    }

    @Override
    public PayVo getOrderPay(String orderSn) {
        OrderEntity order = this.getOrderByOrderSn(orderSn);
        List<OrderItemEntity> orderItemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        PayVo payVo = new PayVo();
        payVo.setTotal_amount((order.getPayAmount().setScale(2, BigDecimal.ROUND_UP)).toString());
        payVo.setOut_trade_no(orderSn);
        payVo.setBody(orderItemEntities.get(0).getSkuName());
        return payVo;
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberResponseVo memberResponseVo = LoginUserIntercepter.loginUser.get();

        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id", memberResponseVo.getId()).orderByDesc("id")
        );

        List<OrderEntity> order_sn = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> orderItemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntityList(orderItemEntities);
            return order;
        }).collect(Collectors.toList());

        page.setRecords(order_sn);

        return new PageUtils(page);
    }

    /**
     * 处理支付宝的付款结果通知
     * @param vo
     * @return
     */
    @Override
    public String handlePayResult(PayAsyncVo vo) {
        // 1、保存交易流水
        PaymentInfoEntity paymentInfoEntity = new PaymentInfoEntity();
        paymentInfoEntity.setAlipayTradeNo(vo.getTrade_no());
        paymentInfoEntity.setOrderSn(vo.getOut_trade_no());
        paymentInfoEntity.setPaymentStatus(vo.getTrade_status());
        paymentInfoEntity.setCallbackTime(vo.getNotify_time());
        boolean save = paymentInfoService.save(paymentInfoEntity);

        // 2、修改订单的状态
        if(vo.getTrade_status().equals("TRADE_SUCCESS") || vo.getTrade_status().equals("TRADE_FINISH")){
            String out_trade_no = vo.getOut_trade_no();
            this.baseMapper.updateOrderStatus(out_trade_no, OrderStatusEnum.PAYED.getCode());
        }

        return "success";
    }

    /**
     * 保存订单到数据库
     * @param order
     * @param loginUser
     */
    private void saveOrder(OrderCreateTO order, MemberResponseVo loginUser) {
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);
        orderEntity.setMemberId(loginUser.getId());
        List<OrderItemEntity> orderItems = order.getOrderItems();
        for (OrderItemEntity itemEntity : orderItems){
            itemEntity.setOrderId(orderEntity.getId());
        }
        orderItemService.saveBatch(orderItems);
    }

    /**
     * 创建订单
     * @param vo
     * @return
     */
    private OrderCreateTO createOrder(OrderSubmitVO vo){
        OrderCreateTO orderCreateTO = new OrderCreateTO();
        // 1、生成订单号
        String timeId = IdWorker.getTimeId();
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(timeId);
        orderEntity.setDeleteStatus(0);

        // 2、获取收获地址信息和运费
        builderAddress(vo, orderEntity);

        // 3、获取到所有的订单项
        List<OrderItemEntity> itemEntities = buildOrderItems(orderEntity.getOrderSn());
        orderCreateTO.setOrderItems(itemEntities);
        orderCreateTO.setOrder(orderEntity);
        // 4、验价
        computePrice(orderEntity, itemEntities);

        return orderCreateTO;
    }

    /**
     * 计算订单价格
     * @param orderEntity
     * @param itemEntities
     */
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> itemEntities) {
        BigDecimal totalPrice = new BigDecimal("0.0");
        BigDecimal couponAmount = new BigDecimal("0.0");
        BigDecimal integerationAmount = new BigDecimal("0.0");
        BigDecimal promotionAmount = new BigDecimal("0.0");
        Integer giftIntegration = 0;
        Integer growthIntegration = 0;
        for (OrderItemEntity itemEntity : itemEntities) {
            couponAmount = couponAmount.add(itemEntity.getCouponAmount());
            integerationAmount = integerationAmount.add(itemEntity.getIntegrationAmount());
            promotionAmount =  promotionAmount.add(itemEntity.getPromotionAmount());
            totalPrice = totalPrice.add(itemEntity.getRealAmount());
            giftIntegration = giftIntegration + itemEntity.getGiftIntegration();
            growthIntegration = growthIntegration + itemEntity.getGiftGrowth();
        }

        orderEntity.setTotalAmount(totalPrice);
        orderEntity.setPayAmount(totalPrice.add(orderEntity.getFreightAmount()));
        orderEntity.setPromotionAmount(promotionAmount);
        orderEntity.setIntegrationAmount(integerationAmount);
        orderEntity.setCouponAmount(couponAmount);
        orderEntity.setGrowth(growthIntegration);
        orderEntity.setIntegration(giftIntegration);

    }

    /**
     * 构建订单中的地址信息和运费
     * @param vo
     * @param orderEntity
     */
    private void builderAddress(OrderSubmitVO vo, OrderEntity orderEntity) {
        R fareR = wmsFeignService.getFare(vo.getAddrId());
        // 远程查询
        FareVO fareResponse = fareR.getData(new TypeReference<FareVO>(){});
        BigDecimal fare = fareResponse.getFare();
        orderEntity.setFreightAmount(fare);
        orderEntity.setReceiverCity(fareResponse.getMemberAddressVO().getCity());
        orderEntity.setReceiverName(fareResponse.getMemberAddressVO().getName());
        orderEntity.setReceiverPhone(fareResponse.getMemberAddressVO().getPhone());
        orderEntity.setReceiverPostCode(fareResponse.getMemberAddressVO().getPostCode());
        orderEntity.setReceiverProvince(fareResponse.getMemberAddressVO().getProvince());
        orderEntity.setReceiverRegion(fareResponse.getMemberAddressVO().getRegion());

        // 设置订单的相关状态信息
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);

    }

    /**
     * 构建订单中的所有商品项
     * @return
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        List<OrderItemVO> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
        if (!CollectionUtils.isEmpty(currentUserCartItems)){
            List<OrderItemEntity> itemEntities = currentUserCartItems.stream().map(item -> {
                OrderItemEntity orderItemEntity = buildOrderItem(item);
                orderItemEntity.setOrderSn(orderSn);
                return orderItemEntity;
            }).collect(Collectors.toList());
            return itemEntities;
        }
        return null;
    }

    /**
     * 构建某一个商品项
     * @param item
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVO item) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        // 1、订单信息：订单号
        // 2、商品的spu信息
        R spuInfoR = productFeignService.getSpuInfoBySkuId(item.getSkuId());
        SpuInfoVO spuInfoResponse = spuInfoR.getData(new TypeReference<SpuInfoVO>() {});
        orderItemEntity.setSpuId(spuInfoResponse.getId());
        orderItemEntity.setSpuName(spuInfoResponse.getSpuName());
        orderItemEntity.setSpuBrand(spuInfoResponse.getBrandId().toString());
        orderItemEntity.setCategoryId(spuInfoResponse.getCatalogId());

        // 3、商品的sku信息
        orderItemEntity.setSkuId(item.getSkuId());
        orderItemEntity.setSkuName(item.getTitle());
        orderItemEntity.setSkuPic(item.getImage());
        orderItemEntity.setSkuPrice(item.getPrice());
        String skuAttrValues = StringUtils.collectionToDelimitedString(item.getSkuAttrValues(), ";");
        orderItemEntity.setSkuAttrsVals(skuAttrValues);
        orderItemEntity.setSkuQuantity(item.getCount());
        // 4、优惠信息（没做）
        // 5、积分信息
        orderItemEntity.setGiftGrowth(item.getPrice().multiply(new BigDecimal(item.getCount().toString())).intValue());
        orderItemEntity.setGiftIntegration(item.getPrice().multiply(new BigDecimal(item.getCount().toString())).intValue());

        // 6、订单项的价格信息
        orderItemEntity.setPromotionAmount(new BigDecimal("0"));
        orderItemEntity.setCouponAmount(new BigDecimal("0"));
        orderItemEntity.setIntegrationAmount(new BigDecimal("0"));
        
        // 7、当前订单项的实际金额
        BigDecimal originPrice = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        BigDecimal realPrice = originPrice.subtract(orderItemEntity.getPromotionAmount())
                .subtract(orderItemEntity.getPromotionAmount())
                .subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(realPrice);
        return orderItemEntity;
    }
}